package com.yancloud.android.contractclient.nativesclient;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.websocket.MessageHandler;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yancloud.android.contractclient.ActionExecutor;
import com.yancloud.android.contractclient.CMClientController;
import com.yancloud.android.contractclient.ResultCallback;

import crypto.SM2;
import crypto.SM2KeyPair;

public class WSHandler implements MessageHandler.Whole<String> {
	public static CMClientController controller;
	ActionExecutor<ResultCallback, JsonObject> ae;
	public static ExecutorService executorService = Executors.newFixedThreadPool(10);
	BaseClient client ;

	public SM2KeyPair keyPair;
	public WSHandler(BaseClient baseClient) {
		client=  baseClient;
		keyPair = new SM2().generateKeyPair();
		controller = new CMClientController(keyPair.getPublicKeyStr());
		ae = new ActionExecutor<>(executorService, controller);
	}

	@Override
	public void onMessage(String arg0) {
		JsonObject arg = new JsonParser().parse(arg0).getAsJsonObject();
		System.out.println("[WSHandler] onMessage:" + arg0);
		if (arg.has("action")) {
			final String action = arg.get("action").getAsString();
			try {
				ae.handle(action, arg, new ResultCallback() {

                    @Override
                    public void onResult(String str) {
                        client.sendText(str);
                    }
                });
			}  catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}